import { useEffect, useState } from 'react';

interface ImageWithLoadingProps {
  src: string;
  alt: string;
  className?: string;
  placeholderClassName?: string;
  [key: string]: any;
}

export const ImageWithLoading = ({
  src,
  alt,
  className = '',
  placeholderClassName = '',
  ...props
}: ImageWithLoadingProps) => {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);

  // Reset loading state when src changes
  useEffect(() => {
    setLoading(true);
    setError(false);
  }, [src]);

  return (
    <div className="relative overflow-hidden">
      {/* Enhanced loading skeleton with shimmer effect */}
      {loading && !error && (
        <div className={`absolute inset-0 bg-gradient-to-r from-gray-200 via-gray-300 to-gray-200 ${placeholderClassName || className}`}>
          <div 
            className="absolute inset-0 bg-gradient-to-r from-transparent via-white to-transparent opacity-40 transform -skew-x-12 animate-pulse"
            style={{
              animation: 'shimmer 2s infinite linear'
            }}
          ></div>
        </div>
      )}
      
      {/* Enhanced error placeholder */}
      {error && (
        <div className={`absolute inset-0 bg-gray-100 flex items-center justify-center ${placeholderClassName || className}`}>
          <div className="text-center text-gray-400">
            <svg className="w-8 h-8 mx-auto mb-2" fill="currentColor" viewBox="0 0 20 20">
              <path fillRule="evenodd" d="M4 3a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V5a2 2 0 00-2-2H4zm12 12H4l4-8 3 6 2-4 3 6z" clipRule="evenodd" />
            </svg>
            <p className="text-xs">Image unavailable</p>
          </div>
        </div>
      )}
      
      {/* Actual image with fade-in effect */}
      <img
        src={src}
        alt={alt}
        className={`${className} transition-all duration-500 ease-out ${
          loading ? 'opacity-0 scale-105' : 'opacity-100 scale-100'
        }`}
        onLoad={() => setLoading(false)}
        onError={() => {
          setLoading(false);
          setError(true);
        }}
        {...props}
      />
    </div>
  );
};